package com.springboot.experiment3;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class GetData {
    private List<RegionStats> data;

    @Scheduled(cron = "0 0 0/1 * * *")
    @PostConstruct
    public void setData() throws IOException {
        data = new ArrayList<>();
        RegionStats regionStats;
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

        //爬取CSV文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = response.getBody();

        //解析CSV文件
        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
            regionStats = new RegionStats();
            regionStats.setState(record.get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt((record.get(record.size()-1))));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            data.add(regionStats);
        }
        System.out.println(data);
    }

    public List<RegionStats> getData() {
        return data;
    }
}
